import java.io.IOException;

import javax.bluetooth.BluetoothStateException;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;


public class ClientConnectionForm extends Form implements GameDiscoveryListener {

	private DisplayController m_Controller;
	private Client m_Client;
	
	public ClientConnectionForm(String title, DisplayController d) {
		super(title);
		m_Controller = d;
		init();
	}
	
	public void init() {
		append("Starting bluetooth client...");
		m_Client = new Client();
		try {
			final GameDiscoverer disc = new GameDiscoverer();
			final GameDiscoveryListener l = this;
			Thread t = new Thread(new Runnable() {
			
				public void run() {
					try {
						disc.start(l);
					} catch (BluetoothStateException e) {
						append("Error during inquiry");
					}
				}
			
			});
			t.start();
		
		} catch (IOException e) {
			append("Error on starting bluetooth server");
		}
	}

	public void discoveryComplete(GameDiscoverer discoverer) {
		
		if (discoverer.serverFount()) {
			String url = discoverer.getConnectionURL();
			m_Client = new Client();
			try {
				m_Client.start(url);
				
				HelicopterCanvas hc;
				hc = new HelicopterCanvas(m_Client);
				m_Controller.setCurrentDisplay(hc);
				hc.start();

			} catch (IOException e) {
				append("Error on starting bluetooth client");
				e.printStackTrace();
			}
		}

		
	}

}
